# TODO: To average tiff file
# 
# Author: phamha
###############################################################################


library(raster)
library(stringr)
library(RPostgreSQL)
dr=dbDriver("PostgreSQL")

str_dbname="fimo"
str_host="192.168.3.4"
str_port=5432
str_user="rasdaman"
str_password="rasdaman"
group_query="SELECT distinct left(filename,17) as str_date from apom.satresampmod04 group by str_date order by str_date asc"
like_query="select filename,filepath from apom.satresampmod04 where filename like '%"

con=dbConnect(dr,dbname=str_dbname,host=str_host,port=str_port,user=str_user,password=str_password)
list_date=dbGetQuery(con,group_query)

for (index in 1:nrow(list_date)) {
	date=list_date[index,1]
	select_query = paste(like_query,date,"%'",sep="")
	list_file=dbGetQuery(con,select_query)
	
	list_full_name=paste("/var/www/html/",str_trim(list_file[,"filepath"],side="both"),str_trim(list_file[,"filename"],side="both"),sep="")
	
	stack_raster=stack()
	for (index2 in 1:length(list_full_name)) {
		full_name=list_full_name[index2]
		stack_raster=addLayer(stack_raster,full_name)
	}
	daily_raster=mean(stack_raster,na.rm=TRUE)
	save_path=substr(list_full_name[1],1,52)
	save_path=str_replace(save_path,"SatResampMOD04","SatResampMOD04_Daily")
	save_path=paste(save_path,"/",date,sep="")
	out_file=paste(save_path,"/",date,".tif",sep="")
	dir.create(save_path,recursive = TRUE)
	writeRaster(daily_raster,filename=out_file,format="GTiff")
	
	
}




